package com.cloud.service.wxuser.impl;

import com.cloud.commons.constants.ConsumeConstant;
import com.cloud.commons.utils.wechat.WeixinUtil;
import com.cloud.dao.wxuser.WxUserDao;
import com.cloud.model.entity.wxuser.WxUser;
import com.cloud.model.view.wxuser.WxUserView;
import com.cloud.service.wxuser.WxUserService;
import com.cloud.commons.utils.CloudCopyUtils;
import com.cloud.commons.utils.JwtUtils;
import com.cloud.service.assetsdetail.AssetsDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
* <b><code>WxUserImpl</code></b>
* <p/>
* WxUser的具体实现
* <p/>
* <b>Creation Time:</b> 2019-10-15 16:15:58.
*
* @author ${model.author}
* @version 1.0.0
* @since cloud-spring-boot-be 1.0.0
*/
@Service
public class WxUserServiceImpl implements WxUserService {

    /**
     * The Constant LOG.
     */
    private static final Logger LOG = LoggerFactory
            .getLogger(WxUserServiceImpl.class);

    @Autowired
    private WxUserDao wxUserDao;

    @Value("${server.port}")
    private String port;

    @Value("${file.sonPath}")
    private String sonPath;


    @Autowired
    private AssetsDetailService assetsDetailService;

    @Override
    public WxUserView getEntity(long id) {
        // 获取Entity
        WxUser wxUser = wxUserDao.findById(id).orElseThrow(() -> new RuntimeException("获取不到用户id为：" + id + "的数据记录"));
        // 复制Dao层属性到view属性
        WxUserView wxUserView = new WxUserView();
        CloudCopyUtils.copyBean(wxUser, wxUserView);
        return wxUserView;
    }

    @Override
    public long getEntitiesCount() {
        return wxUserDao.count();
    }

    @Override
    public List<WxUserView> findAll() {
        List<WxUserView> wxUserViews = new ArrayList<>();
        List<WxUser> wxUsers = wxUserDao.findAll();
        for (WxUser wxUser : wxUsers){
            WxUserView wxUserView = new WxUserView();
            CloudCopyUtils.copyBean(wxUser, wxUserView);
            wxUserViews.add(wxUserView);
        }
        return wxUserViews;
    }

    @Override
    public WxUserView saveEntity(WxUserView wxUserView)  {
        // 保存的业务逻辑
        WxUser wxUser = new WxUser();
        CloudCopyUtils.copyBean(wxUserView, wxUser);
        // user数据库映射传给dao进行存储
        wxUser.setCreateTime(System.currentTimeMillis());
        wxUser.setUpdateTime(System.currentTimeMillis());
        wxUser.setWeight(System.currentTimeMillis());
        wxUser.setMonthBudget(5000L);
        wxUser.setSendMessage(ConsumeConstant.DISABLED);
        wxUser.setEnabled(ConsumeConstant.ENABLED);
        wxUserDao.save(wxUser);
        CloudCopyUtils.copyBean(wxUser,wxUserView);
        return wxUserView;
    }

    @Override
    public void deleteEntity(long id) {
        WxUser wxUser = wxUserDao.findById(id).orElseThrow(() ->new RuntimeException("用户id为：" + id + "的数据已被删除"));
        wxUser.setId(id);
        wxUserDao.delete(wxUser);
    }

    @Override
    @Transactional(rollbackOn = { Exception.class })
    public void deleteEntities(String ids) {
        String[] entityIds= ids.split("\\,");
        List<WxUser> wxUsers = new ArrayList<>();
        for(String entityId : entityIds){
            WxUser wxUser = new WxUser();
            wxUser.setId(Long.valueOf(entityId));
            wxUsers.add(wxUser);
        }
        wxUserDao.deleteInBatch(wxUsers);
    }

    @Override
    public void updateEntity(WxUserView wxUserView) {
        Specification<WxUser> wxUserSpecification = Optional.ofNullable(wxUserView).map( s -> {
            return new Specification<WxUser>() {
                @Override
                public Predicate toPredicate(Root<WxUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    List<Predicate> predicates = new ArrayList<>();
                    // id
                    predicates.add(criteriaBuilder.equal(root.get("id").as(Long.class), s.getId()));

                    criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
                    return criteriaQuery.getRestriction();
                }
            };
        }).orElseThrow(()->new IllegalArgumentException("WxUserView is null"));


        // 获取原有的属性，把不变的属性覆盖
        Optional<WxUser> wxUserOptionalBySearch = wxUserDao.findOne(wxUserSpecification);
        wxUserOptionalBySearch.map(wxUserBySearch -> {
            CloudCopyUtils.copyBeanExcludeNull(wxUserView,wxUserBySearch);
            wxUserBySearch.setUpdateTime(System.currentTimeMillis());
            wxUserDao.save(wxUserBySearch);
            return "";
        }).orElseThrow(()->new RuntimeException("无法找到id为" + wxUserView.getId() + "的数据记录"));
    }

    @Override
    @Transactional
    public WxUserView checkUserLogin(String code) {
        if (ObjectUtils.isEmpty(code)) {
            throw new NullPointerException("code不合法");
        }
        // 进行访问
        String openId = WeixinUtil.code2Session(code);
        // 判断openId是否存在
        WxUser wxUser = wxUserDao.findByOpenId(openId);
        if (!ObjectUtils.isEmpty(wxUser)) {
            WxUserView wxUserView = new WxUserView();
            wxUser.setLoginEndTime(System.currentTimeMillis());
            BeanUtils.copyProperties(wxUser,wxUserView);
            //携带token信息
            wxUserView.setToken(JwtUtils.getToken());
            // 存在记录最后登录时间然后直接返回数据
            updateEntity(wxUserView);
            // 判断当月统计表是否新建
            assetsDetailService.saveAssetsAndAssetsDetail(wxUserView.getId());
            return wxUserView;
        } else {
            // 新建用户信息
            return createWxUserView(openId);
        }
    }

    /**
     * 创建用户基本信息
     * @return
     */
    private WxUserView createWxUserView(String openId) {
        WxUserView wxUserView = new WxUserView();
        // 不存在新建用户信息
        wxUserView.setOpenId(openId);
        // 默认图片信息
        String avatarUrl = "https://be.yangyoki.top:" + port + sonPath + "avatar/avatar.png";
        String nickName = "点击头像获取微信头像、昵称";
        wxUserView.setAvatarUrl(avatarUrl);
        wxUserView.setNickName(nickName);
        wxUserView.setMonthBudget(ConsumeConstant.MONRY_INIT);
        wxUserView.setLoginEndTime(System.currentTimeMillis());
        WxUserView wxUserViewResult =  saveEntity(wxUserView);
        // 新建统计表数据
        assetsDetailService.saveAssetsAndAssetsDetail(wxUserViewResult.getId());
        return wxUserViewResult;
    }
}
